//
//  MJRefresh+Extension.swift
//  Reader
//
//  Created by wsg on 2020/1/2.
//  Copyright © 2020 codeguesser. All rights reserved.
//

import UIKit

import MJRefresh
extension UIViewController{
    typealias MJRefreshFunc = (_ count:Int,_ status:Bool)->Void
    func setupRefresh(tableView:inout UITableView,hasFooter:Bool = true,pageSize:Int=10,refreshData:Bool=true,block:@escaping (_ isheader:Bool,@escaping MJRefreshFunc)->Void) {
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[tableView] in
            block(true){ (count, status) in
                if hasFooter{
                    if status && (count % pageSize > 0 || count == 0){
                        tableView.mj_footer?.endRefreshingWithNoMoreData()
                    }else{
                        tableView.mj_footer?.resetNoMoreData()
                    }
                }
                tableView.mj_header?.endRefreshing()
            }
        })
        if hasFooter{
            let footer = MJRefreshAutoNormalFooter(refreshingBlock:{[tableView] in
                block(false){ count,status  in
                    if status && (count % pageSize > 0 || count == 0){
                        tableView.mj_footer?.endRefreshingWithNoMoreData()
                    }else{
                        tableView.mj_footer?.endRefreshing()
                    }
                }
            })
            tableView.mj_footer = footer
            footer.stateLabel?.textColor = UIColor(named: "TextGray1")
            footer.stateLabel?.font = UIFont.systemFont(ofSize: 12)
        }
        if refreshData{
            tableView.mj_header?.beginRefreshing()
        }
    }
    func setupRefresh(collectionView:inout UICollectionView,hasFooter:Bool = true,pageSize:Int=10,refreshData:Bool=true,block:@escaping (_ isheader:Bool,@escaping MJRefreshFunc)->Void) {
        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[collectionView] in
            block(true){ (count, status) in
                if hasFooter{
                    if status && (count % pageSize > 0 || count == 0){
                        collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    }else{
                        collectionView.mj_footer?.resetNoMoreData()
                    }
                }
                collectionView.mj_header?.endRefreshing()
            }
        })
        if hasFooter{
            collectionView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock:{[collectionView] in
                block(false){ count,status  in
                    if status && (count % pageSize > 0 || count == 0){
                        collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    }else{
                        collectionView.mj_footer?.endRefreshing()
                    }
                }
            })
        }
        if refreshData{
            collectionView.mj_header?.beginRefreshing()
        }
    }
}
